﻿using StackExchange.Redis;
using System.Collections.Concurrent;

namespace XYS.Service.Core.Service
{
    /// <summary>
    /// 缓存服务
    /// </summary>
    public class Cache : ICache
    {
        /// <summary>
        /// redis 数据库 对象
        /// </summary>
        public IDatabase RedisDB { get; set; }

        /// <summary>
        /// 缓存服务
        /// </summary>
        /// <param name="database"></param>
        public Cache(IDatabase database)
        {
            RedisDB = database;
        }




        /// <summary>
        /// 是否存在
        /// </summary>
        /// <param name="cacheKey"></param>
        /// <returns></returns>
        public bool Exists(string cacheKey)
        {
            return RedisDB.KeyExists(cacheKey);
        }

        /// <summary>
        /// 是否存在
        /// </summary>
        /// <param name="cacheKey"></param>
        /// <returns></returns>
        public async Task<bool> ExistsAsync(string cacheKey)
        {
            var redisResult = await RedisDB.ExecuteAsync(cacheKey);
            if (redisResult.IsNull)
                return false;
            return (bool)redisResult;
        }

        /// <summary>
        /// 获取缓存对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="cacheKey"></param>
        /// <returns></returns>
        public T Get<T>(string cacheKey)
        {
            var result = RedisDB.StringGet(cacheKey);
            if (result.IsNull || !result.HasValue)
                return default;
            return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(result);
        }

        /// <summary>
        /// 获取缓存对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="cacheKey"></param>
        /// <returns></returns>
        public async Task<T> GetAsync<T>(string cacheKey)
        {
            var result = await RedisDB.StringGetAsync(cacheKey);
            if (result.IsNull || !result.HasValue)
                return default;
            return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(result);
        }

        /// <summary>
        /// 获取缓存对象
        /// </summary>
        /// <param name="cacheKey"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public async Task<object> GetAsync(string cacheKey, Type type)
        {
            var result = await RedisDB.StringGetAsync(cacheKey);
            if (result.IsNull || !result.HasValue)
                return null;
            return Newtonsoft.Json.JsonConvert.DeserializeObject(result, type);
        }

        private static readonly ConcurrentDictionary<string, SemaphoreSlim> semaphoreSlimMap = new();
        private static SemaphoreSlim GetSemaphoreSlim(string cacheKey)
        {
            if (!semaphoreSlimMap.TryGetValue(cacheKey, out var semaphoreSlim))
            {
                semaphoreSlim = new SemaphoreSlim(1);
                semaphoreSlimMap[cacheKey] = semaphoreSlim;
            }
            return semaphoreSlim;
        }

        /// <summary>
        /// 获取缓存的对象，如果不存在则创建它
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="cacheKey">key</param>
        /// <param name="expiration">失效时间</param>
        /// <param name="factory">如果不存在则调用该委托并进入缓存</param>
        /// <returns></returns>
        public T Get<T>(string cacheKey, TimeSpan? expiration, Func<T> factory)
        {
            var semaphoreSlim = GetSemaphoreSlim(cacheKey);
            semaphoreSlim.Wait();
            try
            {
                var result = Get<T>(cacheKey);
                if (result == null)
                {
                    result = factory.Invoke();
                    if (result != null)
                        Set(cacheKey, result, expiration);
                }
                return result;
            }
            finally { semaphoreSlim.Release(); }
        }

        /// <summary>
        /// 异步获取缓存的对象，如果不存在则创建它
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="cacheKey">key</param>
        /// <param name="expiration">失效时间</param>
        /// <param name="factory">如果不存在则调用该委托并进入缓存</param>
        /// <returns></returns>
        public async Task<T> GetAsync<T>(string cacheKey, TimeSpan? expiration, Func<T> factory)
        {
            var semaphoreSlim = GetSemaphoreSlim(cacheKey);
            await semaphoreSlim.WaitAsync();
            try
            {
                var result = await GetAsync<T>(cacheKey);
                if (result == null)
                {
                    result = factory.Invoke();
                    if (result != null)
                        await SetAsync<T>(cacheKey, result, expiration);
                }
                return result;
            }
            finally { semaphoreSlim.Release(); }
        }


        /// <summary>
        /// 异步获取缓存的对象，如果不存在则创建它
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="cacheKey">key</param>
        /// <param name="expiration">失效时间</param>
        /// <param name="factory">如果不存在则调用该委托并进入缓存</param>
        /// <returns></returns>
        public async Task<T> GetAsync<T>(string cacheKey, TimeSpan? expiration, Func<Task<T>> factory)
        {
            var semaphoreSlim = GetSemaphoreSlim(cacheKey);
            await semaphoreSlim.WaitAsync();
            try
            {
                var result = await GetAsync<T>(cacheKey);
                if (result == null)
                {
                    result = await factory.Invoke();
                    if (result != null)
                        await SetAsync(cacheKey, result, expiration);
                }
                return result;
            }
            finally { semaphoreSlim.Release(); }
        }



        /// <summary>
        /// 移除缓存对象
        /// </summary>
        /// <param name="cacheKey"></param>
        /// <returns></returns>
        public bool Remove(string cacheKey)
        {
            return RedisDB.KeyDelete(cacheKey);
        }

        /// <summary>
        /// 移除缓存对象
        /// </summary>
        /// <param name="cacheKey"></param>
        /// <returns></returns>
        public async Task<bool> RemoveAsync(string cacheKey)
        {
            return await RedisDB.KeyDeleteAsync(cacheKey).ConfigureAwait(false);
        }

        /// <summary>
        /// 设置缓存
        /// </summary>
        /// <returns></returns>
        public bool Set<T>(string cacheKey, T cacheValue, TimeSpan? expiration, When when = When.Always)
        {
            var cacheObj = Newtonsoft.Json.JsonConvert.SerializeObject(cacheValue);
            return RedisDB.StringSet(cacheKey, cacheObj, expiration ?? TimeSpan.FromDays(1), when);
        }

        /// <summary>
        /// 设置缓存
        /// </summary>
        /// <returns></returns>
        public async Task<bool> SetAsync<T>(string cacheKey, T cacheValue, TimeSpan? expiration, When when = When.Always)
        {
            var cacheObj = Newtonsoft.Json.JsonConvert.SerializeObject(cacheValue);
            return await RedisDB.StringSetAsync(cacheKey, cacheObj, expiration ?? TimeSpan.FromDays(1), when).ConfigureAwait(false);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public RedisResult Eval(string script, string[] keys = null, string[] values = null)
        {
            var redisKeys = keys.Select(x => new RedisKey(x)).ToArray();
            var redisValues = values.Select(x => new RedisValue(x)).ToArray();
            var result = RedisDB.ScriptEvaluate(script, redisKeys, redisValues);

            return result;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public async Task<RedisResult> EvalAsync<T>(string script, string[] keys = null, string[] values = null)
        {
            var redisKeys = keys.Select(x => new RedisKey(x)).ToArray();
            var redisValues = values.Select(x => new RedisValue(x)).ToArray();
            var result = await RedisDB.ScriptEvaluateAsync(script, redisKeys, redisValues).ConfigureAwait(false);
            return result;
        }

    }
}
